// MenuExample.js

'use strict';

import React, {Component} from 'react';
import {View, Text, ScrollView} from 'react-native';

import {NavigationPage, Menu, Button, Theme, Label, Overlay, Toast} from 'teaset';

export default class MenuExample extends NavigationPage {

  static defaultProps = {
    ...NavigationPage.defaultProps,
    title: 'Menu',
    showBackButton: true,
  };

  constructor(props) {
    super(props);
    this.btn1Ref = React.createRef();
    this.btn2Ref = React.createRef();
    this.btn3Ref = React.createRef();
    this.btn4Ref = React.createRef();
    this.btn5Ref = React.createRef();
    this.btn6Ref = React.createRef();
    this.directionDownRef = React.createRef();
    this.directionUpRef = React.createRef();
    this.directionLeftRef = React.createRef();
    this.directionRightRef = React.createRef();
    this.iconDemoRef = React.createRef();
    this.titleDemoRef = React.createRef();
    this.shadowRef = React.createRef();
    this.noShadowRef = React.createRef();
    this.arrowTrueRef = React.createRef();
    this.arrowFalseRef = React.createRef();
    this.menuItemComponentRef = React.createRef();
    this.menuViewDirectionDownRef = React.createRef();
    this.menuViewDirectionUpRef = React.createRef();
    this.menuViewDirectionLeftRef = React.createRef();
    this.menuViewDirectionRightRef = React.createRef();
    this.menuViewAlignStartRef = React.createRef();
    this.menuViewAlignCenterRef = React.createRef();
    this.menuViewAlignEndRef = React.createRef();
    this.menuViewArrowTrueRef = React.createRef();
    this.menuViewArrowFalseRef = React.createRef();
    this.menuViewShadowTrueRef = React.createRef();
    this.menuViewShadowFalseRef = React.createRef();
    this.menuViewOpacityZeroRef = React.createRef();
    this.menuViewOpacityDenseRef = React.createRef();
    this.menuViewPointerAutoRef = React.createRef();
    this.menuViewPointerNoneRef = React.createRef();
    this.menuViewModalRef = React.createRef();
    this.menuViewInstance = null;
    this.menuPointerTimeout = null;
  }
    
  componentWillUnmount() {
    if (this.overlayKey) {
      Overlay.hide(this.overlayKey);
      this.overlayKey = null;
    }
    if (this.menuPointerTimeout) {
      clearTimeout(this.menuPointerTimeout);
      this.menuPointerTimeout = null;
    }
  }

  getDefaultItems() {
    return [
      {title: 'Search', icon: require('../icons/search.png'), onPress: () => alert('Search')},
      {title: 'Edit', icon: require('../icons/edit.png'), onPress: () => alert('Edit')},
      {title: 'Remove', icon: require('../icons/trash.png'), onPress: () => alert('Remove')},
    ];
  }

  measureAndShow(view, items, options = {}) {
    if (!view || !view.measure) {
      return;
    }
    view.measure((x, y, width, height, pageX, pageY) => {
      this.overlayKey = Menu.show({x: pageX, y: pageY, width, height}, items, options);
    });
  }

  show(view, align) {
    this.measureAndShow(view, this.getDefaultItems(), {align});
  }

  showIconTypes(view) {
    const items = [
      {title: '带图片图标', icon: require('../icons/search.png'), onPress: () => alert('Image icon')},
      {title: '空图标 (empty)', icon: 'empty', onPress: () => alert('Empty icon')},
      {title: '无图标 (none)', icon: 'none', onPress: () => alert('None icon')},
      {
        title: '自定义组件图标',
        icon: (
          <View style={{width: 20, height: 20, backgroundColor: '#4CAF50', borderRadius: 10, marginRight: 8, justifyContent: 'center', alignItems: 'center'}}>
            <Text style={{color: 'white', fontSize: 12, fontWeight: 'bold'}}>✓</Text>
          </View>
        ),
        onPress: () => alert('Custom icon')
      },
    ];
    this.measureAndShow(view, items);
  }

  showCustomTitle(view) {
    const items = [
      {
        title: (
          <View>
            <Text style={{fontSize: 16, fontWeight: 'bold', color: Theme.menuItemTitleColor}}>主标题</Text>
            <Text style={{fontSize: 12, color: '#999'}}>副标题文字</Text>
          </View>
        ),
        icon: require('../icons/search.png'),
        onPress: () => alert('多行标题')
      },
      {
        title: (
          <Text style={{fontSize: 16, color: '#FF5722', fontWeight: 'bold'}}>删除操作</Text>
        ),
        icon: require('../icons/trash.png'),
        onPress: () => alert('自定义样式')
      },
      {
        title: 2025,
        icon: require('../icons/home_active.png'),
        onPress: () => alert('数字标题 2025'),
      },
      {title: '普通标题', icon: require('../icons/edit.png'), onPress: () => alert('普通')},
    ];
    this.measureAndShow(view, items);
  }

  showWithShadow(view) {
    this.measureAndShow(view, this.getDefaultItems(), {shadow: true});
  }

  showWithoutShadow(view) {
    this.measureAndShow(view, this.getDefaultItems(), {shadow: false});
  }

  showWithDirection(view, direction) {
    this.measureAndShow(view, this.getDefaultItems(), {direction});
  }

  showWithArrow(view, showArrow) {
    this.measureAndShow(view, this.getDefaultItems(), {showArrow});
  }

  showUsingMenuItemsComponent(view) {
    if (!view || !view.measure) {
      return;
    }
    view.measure((x, y, width, height, pageX, pageY) => {
      const fromBounds = {x: pageX, y: pageY, width, height};
      const closeAndAlert = message => {
        if (this.overlayKey) {
          Overlay.hide(this.overlayKey);
          this.overlayKey = null;
        }
        setTimeout(() => alert(message), 10);
      };
      const containerStyle = {
        backgroundColor: Theme.menuColor,
        borderRadius: 6,
        overflow: 'hidden',
      };
      const overlayContent = (
        <Overlay.PopoverView
          fromBounds={fromBounds}
          direction='down'
          align='center'
          showArrow
          shadow
        >
          <View style={containerStyle}>
            <Menu.MenuView.Item
              title='Search'
              icon={require('../icons/search.png')}
              onPress={() => closeAndAlert('Search (Menu.MenuView.Item)')}
            />
            <Menu.MenuView.Item
              title='Edit'
              icon={require('../icons/edit.png')}
              onPress={() => closeAndAlert('Edit (Menu.MenuView.Item)')}
            />
            <Menu.MenuView.Item
              title='Remove'
              icon={require('../icons/trash.png')}
              onPress={() => closeAndAlert('Remove (Menu.MenuView.Item)')}
            />
          </View>
        </Overlay.PopoverView>
      );
      this.overlayKey = Overlay.show(overlayContent);
    });
  }

  clearMenuPointerTimeout() {
    if (this.menuPointerTimeout) {
      clearTimeout(this.menuPointerTimeout);
      this.menuPointerTimeout = null;
    }
  }

  showMenuViewDemo(viewRef, options = {}) {
    const target = viewRef && viewRef.current;
    if (!target || !target.measure) {
      return;
    }
    target.measure((x, y, width, height, pageX, pageY) => {
      const {
        description,
        customItems,
        autoHideDuration,
        ...menuProps
      } = options;
      const items = Array.isArray(customItems) ? customItems : this.getDefaultItems();
      const fromBounds = {x: pageX, y: pageY, width, height};
      const overlayView = (
        <Menu.MenuView
          {...menuProps}
          fromBounds={fromBounds}
          items={items}
          ref={v => this.menuViewInstance = v}
          onDisappearCompleted={() => {
            if (menuProps.onDisappearCompleted) {
              menuProps.onDisappearCompleted();
            }
            this.menuViewInstance = null;
            this.clearMenuPointerTimeout();
          }}
        />
      );
      if (description) {
        Toast.message(description, {position: 'top', duration: 1600});
      }
      if (this.overlayKey) {
        Overlay.hide(this.overlayKey);
        this.overlayKey = null;
      }
      this.overlayKey = Overlay.show(overlayView);
      this.clearMenuPointerTimeout();
      const duration = autoHideDuration || (menuProps.overlayPointerEvents === 'none' ? 2000 : null);
      if (duration) {
        this.menuPointerTimeout = setTimeout(() => {
          if (this.menuViewInstance) {
            this.menuViewInstance.close();
          } else if (this.overlayKey) {
            Overlay.hide(this.overlayKey);
            this.overlayKey = null;
          }
          this.clearMenuPointerTimeout();
        }, duration);
      }
    });
  }

  renderPage() {
    return (
      <ScrollView style={{flex: 1}}>
        <View style={{height: 20}} />
        
        <Label type='detail' size='md' text='基本用法 - align 对齐方式' style={{ fontWeight: 'bold', color: '#000' }} />
        <View style={{height: 10}} />
        <Text style={{marginLeft: 20, marginRight: 20, color: '#999', fontSize: 12, lineHeight: 18}}>
          align 属性演示 - 控制菜单相对触发视图的水平对齐方式 (start/center/end)
        </Text>
        <View style={{height: 60, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around'}}>
          <Button title='Start' ref={this.btn1Ref} onPress={() => this.show(this.btn1Ref.current, 'start')} />
          <Button title='Center' ref={this.btn2Ref} onPress={() => this.show(this.btn2Ref.current, 'center')} />
          <Button title='End' ref={this.btn3Ref} onPress={() => this.show(this.btn3Ref.current, 'end')} />
        </View>
        <View style={{height: 30}} />
        <Label type='detail' size='md' text='direction 弹出方向' style={{ fontWeight: 'bold', color: '#000' }} />
        <View style={{height: 10}} />
        <Text style={{marginLeft: 20, marginRight: 20, color: '#999', fontSize: 12, lineHeight: 18}}>
          direction 属性演示 - 控制菜单从触发点的弹出方向 (down/up/left/right)
        </Text>
        <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', marginBottom: 12}}>
          <Button title='Down' ref={this.directionDownRef} onPress={() => this.showWithDirection(this.directionDownRef.current, 'down')} />
          <Button title='Up' ref={this.directionUpRef} onPress={() => this.showWithDirection(this.directionUpRef.current, 'up')} />
        </View>
        <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'center'}}>
          <Button title='Left' ref={this.directionLeftRef} onPress={() => this.showWithDirection(this.directionLeftRef.current, 'left')} style={{marginRight: 24}} />
          <Button title='Right' ref={this.directionRightRef} onPress={() => this.showWithDirection(this.directionRightRef.current, 'right')} />
        </View>

        <View style={{height: 30}} />
        <Label type='detail' size='md' text='icon 图标类型' style={{ fontWeight: 'bold', color: '#000' }} />
        <View style={{height: 10}} />
        <Text style={{marginLeft: 20, marginRight: 20, color: '#999', fontSize: 12, lineHeight: 18}}>
          icon 属性演示 - 支持字符串枚举 (none/empty)、图片资源，以及自定义组件
        </Text>
        <View style={{alignItems: 'center', marginTop: 10}}>
          <Button 
            title='图标类型演示' 
            type='primary'
            ref={this.iconDemoRef}
            onPress={() => this.showIconTypes(this.iconDemoRef.current)}
          />
        </View>
        
        <View style={{height: 20}} />
        <Label type='detail' size='md' text='title 作为组件' style={{ fontWeight: 'bold', color: '#000' }} />
        <View style={{height: 10}} />
        <Text style={{marginLeft: 20, marginRight: 20, color: '#999', fontSize: 12, lineHeight: 18}}>
          title 属性演示 - 标题可为字符串、数字或 React 组件，实现多行与自定义样式
        </Text>
        <View style={{alignItems: 'center', marginTop: 10}}>
          <Button 
            title='自定义 Title 组件' 
            type='primary'
            ref={this.titleDemoRef}
            onPress={() => this.showCustomTitle(this.titleDemoRef.current)}
          />
        </View>
        
        <View style={{height: 20}} />
        <Label type='detail' size='md' text='shadow 阴影' style={{ fontWeight: 'bold', color: '#000' }}/>
        <View style={{height: 10}} />
        <Text style={{marginLeft: 20, marginRight: 20, color: '#999', fontSize: 12, lineHeight: 18}}>
          shadow 属性演示 - 控制 iOS 上菜单阴影的显示 (true/false)
        </Text>
        <View style={{flexDirection: 'row', justifyContent: 'space-around', marginTop: 10}}>
          <Button 
            title='有阴影' 
            ref={this.shadowRef}
            onPress={() => this.showWithShadow(this.shadowRef.current)}
          />
          <Button 
            title='无阴影' 
            ref={this.noShadowRef}
            onPress={() => this.showWithoutShadow(this.noShadowRef.current)}
          />
        </View>

        <View style={{height: 20}} />
        <Label type='detail' size='md' text='showArrow 箭头' style={{ fontWeight: 'bold', color: '#000' }}/>
        <View style={{height: 10}} />
        <Text style={{marginLeft: 20, marginRight: 20, color: '#999', fontSize: 12, lineHeight: 18}}>
          showArrow 属性演示 - 控制是否显示气泡箭头 (true/false)
        </Text>
        <View style={{flexDirection: 'row', justifyContent: 'space-around', marginTop: 10}}>
          <Button 
            title='显示箭头' 
            ref={this.arrowTrueRef}
            onPress={() => this.showWithArrow(this.arrowTrueRef.current, true)}
          />
          <Button 
            title='隐藏箭头' 
            ref={this.arrowFalseRef}
            onPress={() => this.showWithArrow(this.arrowFalseRef.current, false)}
          />
        </View>

        <View style={{height: 30}} />
        <Label type='detail' size='md' text='Menu.MenuView 直接用法 (覆盖枚举)' style={{ fontWeight: 'bold', color: '#000' }}/>
        <View style={{height: 10}} />
        <Text style={{marginLeft: 20, marginRight: 20, color: '#999', fontSize: 12, lineHeight: 18}}>
          下列示例直接渲染 Menu.MenuView 组件，逐一演示其继承自 Overlay.PopoverView 的枚举属性。
        </Text>
        <View style={{height: 16}} />
        <Label type='detail' size='sm' text='direction (down / up / left / right)' style={{marginLeft: 20}} />
        <View style={{height: 10}} />
        <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
          <Button title='down' ref={this.menuViewDirectionDownRef} onPress={() => this.showMenuViewDemo(this.menuViewDirectionDownRef, {direction: 'down', description: 'Menu.MenuView direction: down'})} />
          <Button title='up' ref={this.menuViewDirectionUpRef} onPress={() => this.showMenuViewDemo(this.menuViewDirectionUpRef, {direction: 'up', description: 'Menu.MenuView direction: up'})} />
          <Button title='left' ref={this.menuViewDirectionLeftRef} onPress={() => this.showMenuViewDemo(this.menuViewDirectionLeftRef, {direction: 'left', description: 'Menu.MenuView direction: left'})} />
          <Button title='right' ref={this.menuViewDirectionRightRef} onPress={() => this.showMenuViewDemo(this.menuViewDirectionRightRef, {direction: 'right', description: 'Menu.MenuView direction: right'})} />
        </View>

        <View style={{height: 20}} />
        <Label type='detail' size='sm' text='align (start / center / end)' style={{marginLeft: 20}} />
        <View style={{height: 10}} />
        <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
          <Button title='start' ref={this.menuViewAlignStartRef} onPress={() => this.showMenuViewDemo(this.menuViewAlignStartRef, {direction: 'down', align: 'start', description: 'Menu.MenuView align: start'})} />
          <Button title='center' ref={this.menuViewAlignCenterRef} onPress={() => this.showMenuViewDemo(this.menuViewAlignCenterRef, {direction: 'down', align: 'center', description: 'Menu.MenuView align: center'})} />
          <Button title='end' ref={this.menuViewAlignEndRef} onPress={() => this.showMenuViewDemo(this.menuViewAlignEndRef, {direction: 'down', align: 'end', description: 'Menu.MenuView align: end'})} />
        </View>

        <View style={{height: 20}} />
        <Label type='detail' size='sm' text='showArrow (true / false)' style={{marginLeft: 20}} />
        <View style={{height: 10}} />
        <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
          <Button title='showArrow: true' ref={this.menuViewArrowTrueRef} onPress={() => this.showMenuViewDemo(this.menuViewArrowTrueRef, {direction: 'down', align: 'center', showArrow: true, description: 'Menu.MenuView showArrow = true'})} />
          <Button title='showArrow: false' ref={this.menuViewArrowFalseRef} onPress={() => this.showMenuViewDemo(this.menuViewArrowFalseRef, {direction: 'down', align: 'center', showArrow: false, description: 'Menu.MenuView showArrow = false'})} />
        </View>

        <View style={{height: 20}} />
        <Label type='detail' size='sm' text='shadow (true / false)' style={{marginLeft: 20}} />
        <View style={{height: 10}} />
        <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
          <Button title='shadow: true' ref={this.menuViewShadowTrueRef} onPress={() => this.showMenuViewDemo(this.menuViewShadowTrueRef, {direction: 'down', shadow: true, description: 'Menu.MenuView shadow = true'})} />
          <Button title='shadow: false' ref={this.menuViewShadowFalseRef} onPress={() => this.showMenuViewDemo(this.menuViewShadowFalseRef, {direction: 'down', shadow: false, description: 'Menu.MenuView shadow = false'})} />
        </View>

        <View style={{height: 20}} />
        <Label type='detail' size='sm' text='overlayOpacity (0 / 0.45)' style={{marginLeft: 20}} />
        <View style={{height: 10}} />
        <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
          <Button title='overlayOpacity: 0' ref={this.menuViewOpacityZeroRef} onPress={() => this.showMenuViewDemo(this.menuViewOpacityZeroRef, {direction: 'down', overlayOpacity: 0, description: 'Menu.MenuView overlayOpacity = 0 (透明背景)'})} />
          <Button title='overlayOpacity: 0.45' ref={this.menuViewOpacityDenseRef} onPress={() => this.showMenuViewDemo(this.menuViewOpacityDenseRef, {direction: 'down', overlayOpacity: 0.45, description: 'Menu.MenuView overlayOpacity = 0.45 (半透明遮罩)'})} />
        </View>

        <View style={{height: 20}} />
        <Label type='detail' size='sm' text='overlayPointerEvents (auto / none)' style={{marginLeft: 20}} />
        <View style={{height: 10}} />
        <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
          <Button title='pointerEvents: auto' ref={this.menuViewPointerAutoRef} onPress={() => this.showMenuViewDemo(this.menuViewPointerAutoRef, {direction: 'down', overlayPointerEvents: 'auto', description: 'Menu.MenuView overlayPointerEvents = auto (遮罩拦截触摸)'})} />
          <Button title='pointerEvents: none' ref={this.menuViewPointerNoneRef} onPress={() => this.showMenuViewDemo(this.menuViewPointerNoneRef, {direction: 'down', overlayPointerEvents: 'none', description: 'Menu.MenuView overlayPointerEvents = none (触摸穿透，2 秒后自动关闭)'})} />
        </View>

        <View style={{height: 20}} />
        <Label type='detail' size='sm' text='modal: true (阻止点击外部关闭)' style={{marginLeft: 20}} />
        <View style={{height: 10}} />
        <View style={{alignItems: 'center'}}>
          <Button title='modal: true 示例' ref={this.menuViewModalRef} onPress={() => this.showMenuViewDemo(this.menuViewModalRef, {direction: 'down', align: 'center', modal: true, overlayOpacity: 0.45, showArrow: true, description: 'Menu.MenuView modal = true (需点击菜单项关闭)'})} />
        </View>

        <View style={{height: 20}} />
        <Label type='detail' size='md' text='直接使用 Menu.MenuView.Item' style={{ fontWeight: 'bold', color: '#000' }}/>
        <View style={{height: 10}} />
        <Text style={{marginLeft: 20, marginRight: 20, color: '#999', fontSize: 12, lineHeight: 18}}>
          下例通过 Overlay.PopoverView 手动渲染 Menu.MenuView.Item 组件，展示如何直接使用官方菜单项类
        </Text>
        <View style={{alignItems: 'center', marginTop: 10}}>
          <Button
            title='使用 Menu.MenuView.Item'
            type='primary'
            ref={this.menuItemComponentRef}
            onPress={() => this.showUsingMenuItemsComponent(this.menuItemComponentRef.current)}
          />
        </View>
        
        <View style={{height: Theme.screenInset.bottom + 20}} />
      </ScrollView>
    );
  }

}
